import time
import cv2
import numpy as np
#https://www.bilibili.com/video/BV1w3411N76g

class Stitcher:
    # 拼接函数
    def stitch(self, images, ratio=0.75, reprojThresh=4.0, showMatches=False):
        # 获取输入图片
        (imageA, imageB) = images #AB反了
        # 检测A、B图片的SIFT关键特征点，并计算特征描述子
        (kpsA, featuresA,kps0A) = self.detectAndDescribe(imageA)
        (kpsB, featuresB,kps0B) = self.detectAndDescribe(imageB)

        # 匹配两张图片的所有特征点，返回匹配结果
        M = self.matchKeypoints(kpsA, kpsB, featuresA, featuresB, ratio, reprojThresh)

        # 如果返回结果为空，没有匹配成功的特征点，退出算法
        if M is None:
            return None

        # 否则，提取匹配结果
        # H是3x3视角变换矩阵
        (matches, H, status,matches0) = M
        print(H)
        widthNew = imageA.shape[1] + int(H[0][2]/H[2][2]) #//原先都在x0，B现在向右移动了一些
        # 将图片B进行视角变换，result是变换后图片
        result = cv2.warpPerspective(imageB, H, (widthNew, imageB.shape[0]))

        # 融合
        # for r in range(result.shape[0]):
        #     left = 0
        #     for c in range(result.shape[1] // 2):
        #         if result[r, c].any():  # overlap
        #             if left == 0:
        #                 left = c
        #             alpha = (c - left) / (result.shape[1] // 2 - left)
        #             result[r, c] = imageB[r, c] * (1 - alpha) + result[r, c] * alpha
        #         else:
        #             result[r, c] = imageB[r, c]

        # 将图片A传入result图片最右端(与上边重复)
        # 重合部分取中间线
        xDiff = (imageA.shape[1]-H[0][2]/H[2][2])/2
        imageA2=imageA[:,0:int(imageA.shape[1]-xDiff)]
        result[0:imageA2.shape[0], 0:imageA2.shape[1]] = imageA2
        #result = result[:,0:int(result.shape[1]*0.6)]#裁切后面黑边
        # 检测是否需要显示图片匹配
        if showMatches:
            # 生成匹配图片
            vis = self.drawMatches(imageA, imageB, kpsA, kpsB, matches[:100], status)
            #vis = cv2.drawMatchesKnn(imageA, kps0A, imageB, kps0B, matches0, None)
            # 返回结果
            return (result, vis)

        # 返回匹配结果
        return result

    def detectAndDescribe(self, image):
        # 将彩色图片转换成灰度图
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        # 建立SIFT生成器
        descriptor = cv2.SIFT_create(nfeatures=5000)#176
        maskTop = np.zeros(imageA.shape[0:2],dtype="uint8")
        cv2.rectangle(maskTop,(0,1400),(imageA.shape[1],imageA.shape[0]),255,-1)
        #gray = cv2.blur(gray,(3,3))
        ret, maskBW = cv2.threshold(gray, 50, 255, cv2.THRESH_BINARY)
        maskAll = cv2.bitwise_and(maskTop,maskBW)
        # 检测SIFT特征点，并计算描述子
        (kps0, features) = descriptor.detectAndCompute(gray, maskAll)
        if(len(features)>=262144):#缩小位置会导致特征点位置发生变化
            #img = self.smallByN(image,3)
            #1.第一种方法 缩小放大
            gray = cv2.resize(gray, None, fx=0.2, fy=0.2, interpolation=cv2.INTER_AREA)
            gray = cv2.resize(gray, None, fx=5, fy=5, interpolation=cv2.INTER_AREA)
            #2.第二种方法 模糊
            #gray = cv2.blur(gray,(3,3))
            #3.第三种方法 全局二值化,局部二值化不起作用
            #ret, gray = cv2.threshold(gray, 186, 255, cv2.THRESH_BINARY)
            (kps0, features) = descriptor.detectAndCompute(gray, maskAll)

        # 将结果转换成NumPy数组
        kps = np.float32([kp.pt for kp in kps0])

        # 返回特征点集，及对应的描述特征
        return kps, features,kps0

    def matchKeypoints(self, kpsA, kpsB, featuresA, featuresB, ratio, reprojThresh):
        # 建立暴力匹配器
        matcher = cv2.DescriptorMatcher_create("BruteForce")

        # 使用KNN检测来自A、B图的SIFT特征匹配对，K=2
        rawMatches = matcher.knnMatch(featuresA, featuresB, 2)

        matches = []
        matches0 = []
        for m in rawMatches:
            # 当最近距离跟次近距离的比值小于ratio值时，保留此匹配对
            if len(m) == 2 and m[0].distance < m[1].distance * ratio:
                # 存储两个点在featuresA, featuresB中的索引值
                matches.append((m[0].trainIdx, m[0].queryIdx))
                matches0.append(m)

        # 当筛选后的匹配对大于4时，计算视角变换矩阵
        if len(matches) > 4:
            # 获取匹配对的点坐标
            ptsA = np.float32([kpsA[i] for (_, i) in matches])
            ptsB = np.float32([kpsB[i] for (i, _) in matches])

            # 计算视角变换矩阵
            #(H, status) = cv2.findHomography(ptsA, ptsB, cv2.RANSAC, reprojThresh)
            (H, status) = cv2.findHomography(ptsB, ptsA, cv2.RANSAC, reprojThresh)
            # 返回结果
            return (matches, H, status,matches0)

        # 如果匹配对小于4时，返回None
        return None

    def drawMatches(self, imageA, imageB, kpsA, kpsB, matches, status):
        # 初始化可视化图片，将A、B图左右连接到一起
        (hA, wA) = imageA.shape[:2]
        (hB, wB) = imageB.shape[:2]
        vis = np.zeros((max(hA, hB), wA + wB, 3), dtype="uint8")
        vis[0:hA, 0:wA] = imageA
        vis[0:hB, wA:] = imageB
        #黑白二值化输出处理
        # vis = cv2.cvtColor(vis, cv2.COLOR_BGR2GRAY)
        # vis = cv2.blur(vis,(5,5))
        # ret, vis = cv2.threshold(vis, 186, 255, cv2.THRESH_BINARY)
        # vis = cv2.cvtColor(vis, cv2.COLOR_GRAY2BGR)
        # 联合遍历，画出匹配对
        for ((trainIdx, queryIdx), s) in zip(matches, status):
            # 当点对匹配成功时，画到可视化图上
            if s == 1:
                # 画出匹配对
                ptA = (int(kpsA[queryIdx][0]), int(kpsA[queryIdx][1]))
                ptB = (int(kpsB[trainIdx][0]) + wA, int(kpsB[trainIdx][1]))
                cv2.line(vis, ptA, ptB, (0, 255, 0), 1)

        # 返回可视化结果
        return vis
    #缩小图像
    def smallByN(self,img, n):
        x, y = img.shape[0:2]
        return cv2.resize(img,(int(y/n),int(x/n)))


if __name__ == '__main__':
    start_time = time.time()
    # 读取拼接图片
    # imageA = cv2.imread("D:\\data\\real\\IMG_5469.JPG")
    # imageB = cv2.imread("D:\\data\\real\\IMG_5470.JPG")
    imageA = cv2.imread(r"D:\data\CUGW\test4\g2\IMG_5354.JPG")
    imageB = cv2.imread(r"D:\data\CUGW\test4\g2\IMG_5355.JPG")

    # 把图片拼接成全景图
    stitcher = Stitcher()
    (result, vis) = stitcher.stitch([imageA, imageB], showMatches=True)
    cv2.imwrite("imgMatches.jpg", vis)
    cv2.imwrite("imgResult.jpg", result)
    end_time = time.time()
    print("共耗时" + str(end_time - start_time))
